package com.qing.demo.netty.client;

import com.qing.demo.netty.util.MsgUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author caozhipeng
 * @date 2025/7/25
 */
public class NettyClient {
    public static void main(String[] args) {
        new NettyClient().connect("127.0.0.1",7379);
    }

    private void connect(String host,int port){
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap=new Bootstrap();
            bootstrap.group(workerGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.AUTO_READ,true);
            bootstrap.handler(new MyChannelInitializer());

            ChannelFuture future = bootstrap.connect(host, port).sync();
            System.out.println("客户端链接success");
            future.channel().writeAndFlush(MsgUtil.buildMsg(future.channel().id().toString(),"hello Server"));
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            workerGroup.shutdownGracefully();
        }
    }
}
